import {$APIMAP, $APIDATA} from '@/api/api.js'
import {isH5} from '@/utils/Platform.js'
const JSON5 = require('json5');
export default {
    methods: {
        throttle: function (duration = 1000) {
            if (this.__buttonLocked) {
                uni.$u.toast('请的操作太快, 请稍后再试');
                throw(new Error('等一等'))
            } else {
                this.__buttonLocked = true;
                setTimeout(() => {
                    this.__buttonLocked = false;
                }, duration);
            }
        },
        getFmtImage: function (v) {
            if (v && v.startsWith('/') && !v.startsWith('/static')) {
                return this.API_PREFIX + v;
            } else {
                return v;
            }
        },
        GM_showModel: function (text) {
            uni.showModal({
                title: '',
                showCancel: false,
                content: text,
            });
        },
        testPing: function (url) {
            return new Promise((resolve, reject) => {
                var flag = false;
                setTimeout(() => {
                    if (!flag) {
                        global.localJSONConfigStarted = 'false';
                        console.log('测试环境JSON服务配置链接超时');
                        resolve({statusCode: 400});
                    }
                }, 3000);
                uni.request({
                    url: url,
                    success: (res) => {
                        flag = true;
                        resolve(res);
                    },
                    fail: (err) => {
                        reject(err);
                    }
                });
            });
        },
        getAndLoad: async function (name, url, arg3) {
            var vm = this;
            if ($APIMAP[name]) {
                url = $APIMAP[name] + url;
            }
            var requestUrl = url;
            if (!url.startsWith('https') && (!url.startsWith('/static') || !isH5)) {
                requestUrl = this.API_PREFIX + url;
            }
            var isDevelopment = false;
            // #ifdef MP-WEIXIN
            isDevelopment = __wxConfig.envVersion == 'develop';
            // #endif
            // #ifdef H5
            isDevelopment = location.hostname == 'localhost';
            // #endif

            // if (!global.localJSONConfigStarted && isDevelopment) {
            //     var result = await this.testPing('http://localhost:8081/remote_assets/wxJSON/menu.js');
            //     console.log(result);
            
            //     if (!result || (result && result.statusCode != 200)) {
            //         global.localJSONConfigStarted = 'false';
            //         console.log('测试环境JSON服务配置未启动， 配置文件服务自动跳转到正式环境');
            //     } else {
            //         global.localJSONConfigStarted = 'true';
            //         console.log('测试环境JSON服务配置是启动的， 配置文件会读本地的配置');
            //     }
            // }
            
            if (global.localJSONConfigStarted == 'true' && isDevelopment && (url.includes('wxJSON') && !url.includes('.jsp'))) {
                requestUrl = 'http://localhost:8081/remote_assets/wxJSON' + url.split('wxJSON')[1];
            }

            var keys = Object.keys($APIDATA);
            var fakeKey = keys.find(key => requestUrl.includes(key));
            
            if (fakeKey) {
                setTimeout(() => {
                    if (typeof arg3 == 'function') {
                        arg3(JSON.parse(JSON.stringify($APIDATA[fakeKey])));
                    } else {
                        (arg3.success || args.complete)(JSON.parse(JSON.stringify($APIDATA[fakeKey])));
                    }
                }, 200);
                return;
            }
            console.log(requestUrl);
            var headers = {};
            
            if (!((name || '').includes('token'))) {
                headers['accessToken'] = uni.getStorageSync('accessToken');
            }
            if (typeof arg3 == 'function') {
                uni.request({
                    url: requestUrl,
                    header: headers,
                    complete: (res => {
                        var rd = '';
                        if (typeof res.data == 'string') {
                            try {
                                rd = JSON5.parse(res.data)
                            } catch (e) {
                                arg3(res.data);
                            }
                        } else {
                            rd = res.data;
                        }
                        if (typeof res.data != 'string' && ( rd.code == '1001' ||  rd.code == '1002')) {
                            vm.doRefreshToken().then(() => {
                                vm.getAndLoad(name, url, arg3);
                            })
                        } else {
                            arg3(rd);
                        }
                    })
                });
            } else {
                uni.request({
                    url: requestUrl,
                    header: headers,
                    ...arg3
                });
            }
        },
        uploadFile: function (url, arg3) {
            var vm = this;
            uni.uploadFile({
                url: vm.API_PREFIX + '/mobile/oa/uploadFile.jsp', // 仅为示例，非真实的接口地址
                filePath: url,
                name: 'file',
                // header: headers,
                formData: {
                    user: 'test'
                },
                complete: (res) => {
                    arg3(JSON.parse(res.data))
                }
            });
        },
        getSessionKey() {
            return new Promise(resolve => {
                var vm = this;
                uni.login({
                    provider: 'weixin',
                    success: function (res) {
                        vm.getAndLoad('获取SK', '/mobile/wx/weChatSessionCode.jsp?code=' + res.code, function (res) {
                            if (res.success) { 
                                resolve(res.data);
                            } else {
                                uni.$u.toast('获取失败');
                            }
                        });
                    }
                });
            });
        },

        getUserLoginInfo: function () {
            var vm = this;
            return new Promise(resolve => {
                vm.getAndLoad('登录', vm.globalConfig.isLoginApi, function(res3) {
                    if (res3.data.exsit) {
                        vm.$store.commit('doLogin', res3.data.userInfo);
                    } else {
                        vm.$store.commit('setUserType', 'tempUser');
                    }
                    resolve({openId: res3.data.openId});
                });
            });
        },

        doRefreshToken: function () {
            var vm = this;
            return new Promise(resolve => {
                function dologin() {
                    uni.login({
                        provider: 'weixin',
                        success: function (res) {
                            vm.getAndLoad('获取token', '/mobile/wx/weChatCode.jsp?code=' + res.code, function (res) {
                                global.tokenApiLock = 0;
                                if (res.success) { 
                                    // uni.setStorageSync('openId', res.openid);
                                    uni.setStorageSync('accessToken', res.accessToken);
                                    uni.setStorageSync('refreshToken', res.refreshToken);
                                    resolve(res);
                                } else {
                                    uni.$u.toast('登录失败');
                                }
                            });
                        }
                    });
                }
                if (global.tokenApiLock) {
                    console.log('过滤重复请求');
                    setTimeout(() => {
                        resolve(vm.doRefreshToken());
                    }, 1000)
                } else {
                    global.tokenApiLock = 1;
                    dologin();
                }
            });
        },
        doWxLogin: function (force) {
            var vm = this;
            var openId = uni.getStorageSync('openId');
            var accessToken = uni.getStorageSync('accessToken');
            var refreshToken = uni.getStorageSync('refreshToken');
            return new Promise(resolve => {
                function codeLogin () {
                    // #ifdef MP-WEIXIN
                    uni.login({
                       provider: 'weixin',
                       success: function (res) {
                           vm.getAndLoad('获取token', '/mobile/wx/weChatCode.jsp?code=' + res.code, function (res) {
                                global.tokenApiLock = 0;
                               if (res.success) { 
                                   // uni.setStorageSync('openId', res.openid);
                                   uni.setStorageSync('accessToken', res.accessToken);
                                   uni.setStorageSync('refreshToken', res.refreshToken);
                                   resolve(res);
                               } else {
                                   uni.$u.toast('登录失败');
                               }
                           });
                       }
                   });
   
                   // #endif
                   // #ifndef MP-WEIXIN
   
                   if (!openId) {
                       if (location.hostname == 'localhost') {
                           openId = 'o52VT5A7Ojgu3A6drKvXchyqtKQ0';
                           resolve({"session_key":"fyIpbSjbqpxFni9FPlYSgA==", "openId": openId, "success":false,"msg":""});
                       } else {
                           uni.showModal({
                               title: '提示',
                               content: '获取登录状态失败',
                               showCancel: false,
                               success: function(res2) {
                                   location.href = '/';
                               }
                           });
                       }
                   } else {
                       resolve({"session_key":"fyIpbSjbqpxFni9FPlYSgA==", "openId": openId, "success":false,"msg":""});
                   }
                   // #endif
                }

                if (accessToken && refreshToken && !force) {
                    if (openId) {
                        resolve({openId: openId})
                    } else {
                        vm.getUserLoginInfo().then(res3 => {
                            resolve(res3)
                        });
                    }
                } else {
                    if (global.tokenApiLock) {
                        console.log('过滤重复请求');
                        setTimeout(() => {
                            resolve(vm.doWxLogin());
                        }, 1000)
                    } else {
                        global.tokenApiLock = 1;
                        codeLogin();
                    }
                }
            });

        }
    }
}